package com.fs.ibox.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fs.ibox.dao.UserDao;
import com.fs.ibox.pojo.Orders;
import com.fs.ibox.pojo.User;
import com.fs.ibox.service.OrdersService;
import com.fs.ibox.service.UserService;
import com.fs.ibox.util.BeanFactory;
import com.fs.ibox.util.FileUploadUitl;
import com.fs.ibox.util.ResponseDataUtil;
import com.fs.ibox.vo.*;
import com.fs.ibox.util.ResponseJSONUtil;
import com.fs.ibox.vo.ResponseData;
import com.fs.ibox.vo.ResultEnums;
import com.fs.ibox.vo.UserCollection;
import com.fs.ibox.vo.ShowcollVO;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet(name = "UserServlet", value = "/user/*")
public class UserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.设置编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");



        String path = request.getPathInfo();
        if("/login".equals(path)){
            login(request,response);
        }



        else if("/register".equals(path)){
            try {
                register(request,response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if("/showcoll".equals(path)){
            showcoll(request,response);
        }else if("/showcollinto".equals(path)){
            showCollInto(request,response);
        }else if ("/sellcoll".equals(path)){
            sellColl(request,response);
        }else if("/sale".equals(path)){
            sale(request,response);
        }else if("/cancelsale".equals(path)){
            cancelsale(request,response);
        }
        else if("/queryAllOrders".equals(path)){
            queryAllOrders(request,response);
        }
        else if("/delById".equals(path)){
            delById(request,response);
        }else if ("/update".equals(path)){
            update(request,response);
        }


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.设置编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        String path = request.getPathInfo();

        if("/queryMoney".equals(path)) {
            queryMoney(request, response);
        }
    }

    private void queryMoney(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String username = request.getParameter("user");
        System.out.println(username);
        UserService bean = BeanFactory.createBean(UserService.class);
        Double money = bean.queryMoney(username);
        System.out.println(money);
        System.out.println(JSON.toJSONString(money));
        ResponseData responseData = ResponseDataUtil.buildOk(money);
        ResponseJSONUtil.responseJSON(responseData, response);
    }

    private void delById(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");
        int Intid=Integer.parseInt(id);
        OrdersService bean = BeanFactory.createBean(OrdersService.class);
        bean.delById(Intid);
        ResponseData mmsg = ResponseDataUtil.buildOk("删除成功");
        ResponseJSONUtil.responseJSON(mmsg,response);
    }

    private void queryAllOrders(HttpServletRequest request, HttpServletResponse response) throws IOException {
        OrdersService bean = BeanFactory.createBean(OrdersService.class);
        List<Orders> orders = bean.queryOrdersAll();
        ResponseData responseData = ResponseDataUtil.buildOk(orders);
        ResponseJSONUtil.responseJSON(responseData,response);
    }




    /**
     * 取消上架方法
     * @param request
     * @param response
     */
    private void cancelsale(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {



        //获取前端传递的json数据
        StringBuffer stringBuffer = new StringBuffer();
        //请求输入流
        BufferedReader reader = request.getReader();
        String line = null;

        while((line = reader.readLine()) != null){
            stringBuffer.append(line);
        }
        //获取json中的数据
        JSONObject js = JSON.parseObject(stringBuffer.toString());


        String cname = js.getString("cname");
        String cid = js.getString("cid");

        UserService bean = BeanFactory.createBean(UserService.class);
        int reg = bean.cancelsale(cname,cid);

        String json = "";

        PrintWriter writer = response.getWriter();
        if (reg != 0){
            //取消上架成功
            ResponseData<Integer> r = ResponseDataUtil.buildOk(reg);

            json = JSON.toJSONString(r);
        }else {
            json = JSON.toJSONString(ResponseDataUtil.buildOk(ResultEnums.CANCELSALE_FAIL));
        }
        //写入输出流
        writer.print(json);
        writer.flush();
    }



    /**
     * 用户正在售卖的藏品信息展示
     * @param request
     * @param response
     * @throws IOException
     */
    private void sale(HttpServletRequest request, HttpServletResponse response) throws IOException {


        //获取前端传递的json数据
        StringBuffer stringBuffer = new StringBuffer();
        //请求输入流
        BufferedReader reader = request.getReader();
        String line = null;

        while((line = reader.readLine()) != null){
            stringBuffer.append(line);
        }
        //获取json中的数据
        JSONObject js = JSON.parseObject(stringBuffer.toString());

        String username = js.getString("username");


        UserService bean = BeanFactory.createBean(UserService.class);
        List<SaleVO> reg = bean.sale(username);

        String json = "";

        PrintWriter writer = response.getWriter();
        if (reg != null){
            //上架成功
            ResponseData<Integer> r = ResponseDataUtil.buildOk(reg);

            json = JSON.toJSONString(r);
        }else {
            json = JSON.toJSONString(ResponseDataUtil.buildOk(ResultEnums.REGISTER_FAIL));
        }
        //写入输出流
        writer.print(json);
        writer.flush();
    }

    /**
     * 卖出藏品
     * @param request
     * @param response
     * @throws IOException
     */
    private void sellColl(HttpServletRequest request, HttpServletResponse response) throws IOException {

        //获取前端传递的json数据
        StringBuffer stringBuffer = new StringBuffer();
        //请求输入流
        BufferedReader reader = request.getReader();
        String line = null;

        while((line = reader.readLine()) != null){
            stringBuffer.append(line);
        }
        //获取json中的数据
        JSONObject js = JSON.parseObject(stringBuffer.toString());

        String cname = js.getString("cname");
        String cid = js.getString("cid");
        String price = js.getString("price");

        System.out.println(price);

        double priceDouble = Double.parseDouble(price);
        System.out.println(priceDouble);

        UserService bean = BeanFactory.createBean(UserService.class);
        int reg = bean.sellColl(cname,cid,priceDouble);
        String json = "";

        PrintWriter writer = response.getWriter();
        if (reg != 0){
            //上架成功
            ResponseData<Integer> r = ResponseDataUtil.buildOk(reg);

            json = JSON.toJSONString(r);
        }else {
            json = JSON.toJSONString(ResponseDataUtil.buildOk(ResultEnums.REGISTER_FAIL));
        }
        //写入输出流
        writer.print(json);
        writer.flush();
    }

    /**
     * 修改用户信息
     *
     * @param request
     * @param response
     */
    private void update(HttpServletRequest request, HttpServletResponse response) throws IOException {

        User user = new User();
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
        ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);

        try {
            List<FileItem> fileItems = servletFileUpload.parseRequest(request);
            for (FileItem fileItem : fileItems) {
                if (fileItem.isFormField()){
                    // 普通字段
                    String fieldName = fileItem.getFieldName();
                    String value = new String(fileItem.getString().getBytes("iso8859-1"), "UTF-8");
                    if (fieldName.equals("username")){
                        user.setUserName(value);
                    }else if (fieldName.equals("nickname")){
                        user.setNickName(value);
                    }
                }else{
                    // 文件字段
                    String path="E:\\JavaCode\\ibox\\前台\\后端\\ibox\\img";
                    String name = fileItem.getName();
                    String saveFile = FileUploadUitl.randomFilename() + FileUploadUitl.getSuffix(name);
                    System.out.println(saveFile);
                    user.setHeadportrait("/img/"+saveFile);
                    fileItem.write(new File(path,saveFile));
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        UserService bean = BeanFactory.createBean(UserService.class);
        int i = bean.update(user);
        ResponseData responseData = null;
        PrintWriter writer = response.getWriter();
        String s = null;
        if (i > 0) {
            responseData = ResponseDataUtil.buildOk(i);

        }else {
            responseData = ResponseDataUtil.buildOk(ResultEnums.UPDATEFAIL);
        }
        s = JSON.toJSONString(responseData);
        writer.print(s);
        writer.flush();

    }

    /**
     * 用户点击某个昌平，该藏品的具体详情展示方法
     * @param request
     * @param response
     * @throws IOException
     */
    private void showCollInto(HttpServletRequest request, HttpServletResponse response) throws IOException  {


        //获取前端传递的json数据
        StringBuffer stringBuffer = new StringBuffer();
        //请求输入流
        BufferedReader reader = request.getReader();
        String line = null;

        while((line = reader.readLine()) != null){
            stringBuffer.append(line);
        }
        //获取json中的数据
        JSONObject js = JSON.parseObject(stringBuffer.toString());

        String username= js.getString("username");
        String cname= js.getString("cname");
        System.out.println(username);

        UserService bean = BeanFactory.createBean(UserService.class);
        ShowcollVO reg = bean.showCollInto(username,cname);
        String json = "";
        PrintWriter writer = response.getWriter();
        if (reg != null){
            //登录成功
            ResponseData<User> r = ResponseDataUtil.buildOk(reg);

            json = JSON.toJSONString(r);
        }else {
            json = JSON.toJSONString(ResponseDataUtil.buildOk(ResultEnums.REGISTER_FAIL));
        }
        //写入输出流
        writer.print(json);
        writer.flush();
    }

    private void login(HttpServletRequest request, HttpServletResponse response) throws IOException {

        //获取前端传递的json数据
        StringBuffer stringBuffer = new StringBuffer();
        //请求输入流
        BufferedReader reader = request.getReader();
        String line = null;

        while((line = reader.readLine()) != null){
            stringBuffer.append(line);
        }
        //获取json中的数据
        JSONObject js = JSON.parseObject(stringBuffer.toString());

        String username = js.getString("username");
        String password = js.getString("password");


        User user = new User();

        user.setUserName(username);
        user.setPassword(password);
//        Integer intId=Integer.getInteger(id);
        UserService bean = BeanFactory.createBean(UserService.class);
        User login = bean.login(user);
        String json = "";
        PrintWriter writer = response.getWriter();
        if (login != null){
            //登录成功
            ResponseData<User> r = ResponseDataUtil.buildOk(login);

            json = JSON.toJSONString(r);
        }else {
            json = JSON.toJSONString(ResponseDataUtil.buildOk(ResultEnums.LOGIN_ERR));
        }
        System.out.println(json);
        //写入输出流
        writer.print(json);
        writer.flush();
    }

    /**
     * 注册方法，想user表中插入username和password
     * @param request
     * @param response
     * @throws IOException
     */
    private void register(HttpServletRequest request,HttpServletResponse response) throws IOException{

        //获取前端传递的json数据
        StringBuffer stringBuffer = new StringBuffer();
        //请求输入流
        BufferedReader reader = request.getReader();
        String line = null;

        while((line = reader.readLine()) != null){
            stringBuffer.append(line);
        }
        //获取json中的数据
        JSONObject js = JSON.parseObject(stringBuffer.toString());

        String username = js.getString("username");
        String password = js.getString("password");


        User user = new User();

        user.setUserName(username);
        user.setPassword(password);
        user.setMoney((double) 0);
        user.setState(0);
        user.setNum(0);
//        System.out.println("@@"+user.toString());
//        Integer intId=Integer.getInteger(id);
        UserService bean = BeanFactory.createBean(UserService.class);
        int reg = bean.register(user);
        String json = "";
        PrintWriter writer = response.getWriter();
        if (reg != 0){
            //登录成功
            ResponseData<User> r = ResponseDataUtil.buildOk(reg);

            json = JSON.toJSONString(r);
        }else {
            json = JSON.toJSONString(ResponseDataUtil.buildOk(ResultEnums.REGISTER_FAIL));
        }
        System.out.println(json);
        //写入输出流
        writer.print(json);
        writer.flush();
    }

    /**
     * 展示所有用户所有藏品方法，得到前端的用户账号
     * 去藏品id表查询
     * @param request
     * @param response
     */
    private void showcoll(HttpServletRequest request,HttpServletResponse response) throws IOException{


        //获取前端传递的json数据
        StringBuffer stringBuffer = new StringBuffer();
        //请求输入流
        BufferedReader reader = request.getReader();
        String line = null;

        while((line = reader.readLine()) != null){
            stringBuffer.append(line);
        }
        //获取json中的数据
        JSONObject js = JSON.parseObject(stringBuffer.toString());

        String username = js.getString("username");

        User user = new User();
        user.setUserName(username);

        UserService bean = BeanFactory.createBean(UserService.class);
        List<UserCollection> reg = bean.showColl(user);
        String json = "";
        PrintWriter writer = response.getWriter();
        if (reg != null){
            //登录成功
            ResponseData<User> r = ResponseDataUtil.buildOk(reg);

            json = JSON.toJSONString(r);
        }else {
            json = JSON.toJSONString(ResponseDataUtil.buildOk(ResultEnums.REGISTER_FAIL));
        }
        //写入输出流
        writer.print(json);
        writer.flush();
    }

}
